#include "SubsessionEventHandler.h"
#include "SubSessionMgr.h"
#include "Proxy.h"
#include "ut_debug.h"

CSubsessionEventHandler::CSubsessionEventHandler( utility::network::session * s )
{
    m_pSession = s;
    m_pProxy = NULL;
}


CSubsessionEventHandler::~CSubsessionEventHandler(void)
{
    m_pSession = NULL;
    m_pProxy = NULL;
}

void CSubsessionEventHandler::on_receive( const char * message, uint32 message_length )
{
    if (m_pProxy)
        m_pProxy->OnCliReceive(message, message_length);
}

void CSubsessionEventHandler::on_established()
{
    if (m_pProxy)
        m_pProxy->OnCliConnected();
}

void CSubsessionEventHandler::on_disconnected()
{
    if (m_pProxy)
        m_pProxy->OnCliDisconnected();
    m_pSession = NULL;
    CSubSessionMgr::Instance()->RecycleEventHandler(this);
}

void CSubsessionEventHandler::on_error( int32 error_code, const char * error_message )
{
    LOG(CRITICAL) << "Network error, code number" << error_code << ", message:"<<error_message;
    if (m_pProxy)
        m_pProxy->OnCliError(error_code, error_message);
    m_pSession = NULL;
    CSubSessionMgr::Instance()->RecycleEventHandler(this);
}

void CSubsessionEventHandler::send( void * message, size_t message_length )
{
    if (m_pSession)
        m_pSession->send(message, message_length);
}

void CSubsessionEventHandler::SetProxy( CProxy * pProxy )
{
    m_pProxy = pProxy;
}

void CSubsessionEventHandler::Disconnect()
{
    if (m_pSession)
        m_pSession->disconnect();
}
